﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml.Linq;

namespace mVu
{
  abstract class Site
  {
    public abstract Dictionary<string, string> GetCategories();
    public abstract Dictionary<string, string> GetSorts();
    public abstract Dictionary<string, string> GetMediaTypes();
    public abstract List<Thumbnail> GetThumbnails(string baseAddress, string sort, string query, int page);
    public abstract Dictionary<string, string> GetVideoPaths(string url);

    protected static string GetPageSource(string url)
    {
      var result = String.Empty;

      try
      {
        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Proxy = null;
        request.UserAgent = "Mozilla/4.0";
        request.Timeout = 600000;
        request.Credentials = CredentialCache.DefaultCredentials;

        using (var response = (HttpWebResponse)request.GetResponse())
        {
          using (var stream = response.GetResponseStream())
          {
            using (var reader = new StreamReader(stream))
            {
              result = reader.ReadToEnd();
            }
          }
        }
      }
      catch (Exception ex)
      {
        Utilities.HandleError(ex);
      }

      return result;
    }

    protected static string ShortenURL(string url)
    {
      try
      {
        string xml = GetPageSource(String.Format("http://ur.ly/new.xml?href={0}", Uri.EscapeDataString(url)));
        var doc = XDocument.Parse(xml);
        string code = doc.Descendants("urly").Attributes("code").First().Value;
        return (String.Format("http://ur.ly/{0}", code));
      }
      catch (Exception ex)
      {
        Utilities.HandleError(ex);
      }

      return url;
    }
  }
}
